package com.example.projectmanagement.service;

import com.example.projectmanagement.dto.ApiMonitorDto;
import com.example.projectmanagement.dto.ApiEndpointDto;
import com.example.projectmanagement.interceptor.ApiEndpointStatistics;
import com.example.projectmanagement.interceptor.ApiMonitorInterceptor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ApiMonitorService {

    /**
     * 获取真实的API监控数据
     */
    public ApiMonitorDto getRealApiMonitorData() {
        ApiMonitorDto apiMonitor = new ApiMonitorDto();
        
        // 获取真实的API统计数据
        Map<String, ApiEndpointStatistics> apiStats = ApiMonitorInterceptor.getApiStats();
        List<ApiEndpointDto> topEndpoints = convertToApiEndpointDto(new ArrayList<>(apiStats.values()));
        
        // 计算总请求数和错误请求数
        long totalRequests = 0;
        long errorRequests = 0;
        double totalResponseTime = 0;
        
        for (ApiEndpointDto endpoint : topEndpoints) {
            totalRequests += endpoint.getRequestCount();
            errorRequests += endpoint.getErrorCount();
            totalResponseTime += endpoint.getAvgResponseTime() * endpoint.getRequestCount();
        }
        
        apiMonitor.setTotalRequests(totalRequests);
        apiMonitor.setErrorRequests(errorRequests);
        apiMonitor.setAvgResponseTime(totalRequests > 0 ? Math.round((totalResponseTime / totalRequests) * 10000.0) / 10000.0 : 0);
        apiMonitor.setMonitorTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        apiMonitor.setTopEndpoints(topEndpoints);
        
        return apiMonitor;
    }
    
    /**
     * 将ApiEndpointStatistics转换为ApiEndpointDto
     */
    private List<ApiEndpointDto> convertToApiEndpointDto(List<ApiEndpointStatistics> statisticsList) {
        return statisticsList.stream().map(stat -> {
            ApiEndpointDto dto = new ApiEndpointDto();
            dto.setUrl(stat.getUrl());
            dto.setMethod(stat.getMethod());
            dto.setRequestCount(stat.getRequestCount());
            dto.setErrorCount(stat.getErrorCount());
            dto.setAvgResponseTime(Math.round(stat.getAvgResponseTime() * 10000.0) / 10000.0);
            dto.setMinResponseTime(stat.getMinResponseTime());
            dto.setMaxResponseTime(stat.getMaxResponseTime());
            dto.setSuccessRate(Math.round(stat.getSuccessRate() * 100.0) / 100.0);
            if (stat.getLastAccessTime() != null) {
                dto.setLastAccessTime(stat.getLastAccessTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            return dto;
        }).collect(Collectors.toList());
    }
    
    /**
     * 重置所有API统计信息
     */
    public void resetAllApiStats() {
        ApiMonitorInterceptor.resetApiStats();
    }
    
    /**
     * 根据时间重置API统计信息
     */
    public void resetApiStatsByTime(int hours) {
        ApiMonitorInterceptor.resetApiStatsByTime(hours);
    }
}